package org.sng.util.xml;

public class XmlNode {
	
	private XmlNode m_next;
	private XmlNode m_childNode;
	
	private String m_id;
	private StringBuffer m_data;
	
	public XmlNode(String name)
	{
		this.m_next = null;
		this.m_childNode = null;
		
		this.m_id = name;
		this.m_data = null;
	}
	
	public void addDataNode(String text)
	{
		this.m_data = new StringBuffer();
		
		this.m_data.append("<![CDATA[");
		this.m_data.append(text);
		this.m_data.append("]]>");
	}
	
	public void addTextNode(String text)
	{
		this.m_data = new StringBuffer();
		
		this.m_data.append(text);
	}
	
	public void addProp(String name, String value)
	{
		
	}
	
	public void addChildNode(XmlNode node)
	{
		if (this.m_childNode != null)
		{
			this.m_childNode.appendNode(node);
		}
		else
		{
			this.m_childNode = node;
		}
	}
	
	public void appendNode(XmlNode node)
	{
		if (this.m_next != null)
		{
			this.m_next.appendNode(node);
		}
		else
		{
			this.m_next = node;
		}
	}
	
	public void output(StringBuffer sb)
	{
		sb.append("<");
		sb.append(this.m_id);
		sb.append(">");
		
		if (this.m_childNode != null)
		{
			this.m_childNode.output(sb);
		}
		else if (this.m_data != null) {
			sb.append(this.m_data);
		}
		
		sb.append("</");
		sb.append(this.m_id);
		sb.append(">");
		
		if (this.m_next != null)
		{
			this.m_next.output(sb);
		}
	}
	
	public String toFile()
	{
		StringBuffer sb = new StringBuffer();
		
		sb.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
		
		this.output(sb);
		
		return sb.toString();
	}
	
	public static XmlNode CreateDataNode(String id, String content)
	{
		XmlNode o = new XmlNode(id);
		
		if (content != null)
		{
			o.addDataNode(content);
		}
		
		return o;
	}
	
	public static XmlNode CreateTextNode(String id, String content)
	{
		XmlNode o = new XmlNode(id);
		
		if (content != null)
		{
			o.addTextNode(content);
		}
		
		return o;
	}
}
